package com.zhengyisky.service;

import com.zhengyisky.dao.UserRepository;
import com.zhengyisky.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserRepository userRepository;

    public User findUserByOpenid(String baiduId) {
        return userRepository.findUserByOpenid(baiduId);
    }

    public Boolean haveAccount(User user) {
        User u = userRepository.findUserByPhoneAndPassword(user.getPhone(),user.getPassword());
        if(u==null){
            return false;
        }else{
            u.setOpenid(user.getOpenid());
            userRepository.save(u);
            return true;
        }
    }

    public Boolean noAccount(User user) {
        User u = userRepository.findUserByPhone(user.getPhone());
        if(u!=null){
            return false;
        }else{
            user.setUserRole("BORROWERS");
            user.setStatus(0);
            userRepository.save(user);
            return true;
        }
    }

    public Map getUserInfo(String phone) {
        Map<Object, Object> user = redisTemplate.opsForHash().entries("info"+phone);
        if(user.isEmpty()){
            User u = userRepository.findUserByPhone(phone);
            user = new HashMap();
            user.put("realname",u.getRealname());
            user.put("idcard",u.getIdcard());
            user.put("status",u.getStatus()+"");
            redisTemplate.opsForHash().putAll("info"+phone,user);
        }
        return user;
    }

    @Transactional
    public void updateUserStatus(String mobile, Integer status) {
        userRepository.updateStatusByPhone(mobile,status);
        redisTemplate.delete("info"+mobile);
    }
}
